package it.apiconsulting.sharem.dao;


import it.apiconsulting.sharem.model.Playlist;
import it.apiconsulting.sharem.util.HibernateUtil;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;


public class PlaylistDao extends HibernateUtil {
	
	public Playlist add(Playlist playlist) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(playlist);
		session.getTransaction().commit();
		return playlist;
	}
	public Playlist delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Playlist playlist = (Playlist) session.load(Playlist.class, id);
		if(null != playlist) {
			session.delete(playlist);
		}
		session.getTransaction().commit();
		return playlist;
	}

	public List<Playlist> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Playlist> playlists = null;
		try {
			
			Query query = session.createQuery("from Playlist");
			playlists = (List<Playlist>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return playlists;
	}
	
	public List<Playlist> listByIdUser( Long idUser ) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Playlist> playlists = null;
		try {
			
			Query query = session.createQuery("from Playlist as p where p.idUser=" + idUser);
			playlists = (List<Playlist>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return playlists;
	}
}
